<?php

class SatisfyAction extends CommonAction {
	private $prize_type = 'satisfy';
	private $_description = array ('1' => '成功领取奖品', '-1' => '打卡天数不够', '-2' => '已经领取该奖品', '-3' => '你来晚了，奖品被领光了', '-4' => '数据库出错');
	
	public function showPrize() {
		$join = ' ws_prize_store on ws_prize_satisfy.prst_id=ws_prize_store.prst_id ';
		return M ( 'PrizeSatisfy' )->join ( $join )->select ();
	}
	
	# 领取奖品
	public function receivePrize() {
		$spr_id = $_REQUEST['spr_id'];
		$uid = $this->Core->User->u_id;
		$user = getInfoById ( 'User', $uid );
		$spr = getInfoById ( 'PrizeSatisfy', $spr_id );
		
		$_result = $this->checkSatisfy ( $user, $spr );
		
		if ($_result == 1)
			$_result = $this->checkRepeat ( $user, $spr );
		
		if ($_result == 1)
			$_result = $this->checkPrizeCount ( $spr );
		
		if ($_result == 1)
			$_result = $this->onPrize ( $user, $spr );
		
		$_rdata = array ('status' => $_result, 'msg' => $this->_description [$_result] );
		die ( json_encode ( $_rdata ) );
	}
	
	# 检查获取奖品资格
	private function checkSatisfy($user, $spr) {
		return ($user ['u_carddays'] < $spr ['spr_satisfy_carddays']) ? - 1 : 1;
	}

	# 检查是否已经获取
	private function checkRepeat($user, $spr) {
		$_repdata ['rep_type'] = $this->prize_type;
		$_repdata ['u_id'] = $user ['u_id'];
		$_repdata ['prst_id'] = $spr ['prst_id'];
		$rep = M ( 'RecordPrize' )->where ( $_repdata )->find ();
		return $rep ? - 2 : 1;
	}
	
	# 检查奖品库存是否足够
	private function checkPrizeCount($spr) {
		return $spr['spr_count']>0 ? 1 : - 3;
	}
	
	# 获取奖品，写入日志
	private function onPrize($user, $spr) {
		# 扣去库存
		$_sprdata['spr_count'] = ($spr['spr_count'] - 1>0) ? $spr['spr_count'] - 1 : 0;
		$_spr['spr_id'] = $spr['spr_id'];
		M('PrizeSatisfy')->where($_spr)->data($_sprdata)->save();
		
		# 写入日志
		$params ['rep_type'] = $this->prize_type;
		$params ['u_id'] = $user ['u_id'];
		$params ['prst_id'] = $spr ['prst_id'];
		$params ['rep_description'] = $user ['u_mobile'] . ' ' . $spr ['spr_description'];
		A ( 'Record' )->onAdd ( 'Prize', $params );
		return 1;
		
		
	}
}
?>